//
//  WYJNetworkTool.swift
//  网络工具类的封装
//
//  Created by eastriver on 16/10/6.
//  Copyright © 2016年 eastriver. All rights reserved.
//

import UIKit
import AFNetworking
enum HTTPMethod {
    case POST
    case GET
}
class WYJNetworkTool: AFHTTPSessionManager {
    //声明单例对象
    static let sharedTool: WYJNetworkTool = {
        let tool = WYJNetworkTool()
        tool.responseSerializer.acceptableContentTypes?.insert("text/html")
        tool.responseSerializer.acceptableContentTypes?.insert("text/plain")
            // 修改超时时间为30s
            tool.requestSerializer.timeoutInterval = 30
        return tool
    }()
    
    //封装核心方法
    func request(method: HTTPMethod, urlString: String, parameters: Any?, finished: @escaping (Any?,Error?) -> ()) {
        //提前定义失败和成功的闭包 将闭包当做参数传递
        //成功的回调
        let successCallBack = { (task: URLSessionDataTask,responseObject: Any?) -> () in
            //这里需要使用到参数
            finished(responseObject, nil)
        }
        
        //失败的回调
        let failureCallBack = { (task: URLSessionDataTask?, error: Error) -> () in
            //输出错误信息
            print(error)
            finished(nil, error)
        }
        //判断method 做出相应的网络请求
        if method == .GET {
            get(urlString, parameters: parameters, progress: nil, success: successCallBack, failure: failureCallBack)
        } else {
            post(urlString, parameters: parameters, progress: nil, success: successCallBack, failure: failureCallBack)
        }
    }
    
}
